import {IElement} from "./IElement";
import {IXMLDocument} from "./IXMLDocument";
import {NodeJsElement} from "./NodeJsElement";
import {DOMParser} from "xmldom"
import { NS_STREAM } from "./JSJaCConstants";
/**
 * 基于xmldom的xml解析实现
 */
export class NodeJsXMLDocument extends NodeJsElement implements IXMLDocument {

    private doc:Document;
    private rootElement:IElement;
    constructor(xml:string,name:string,namespacesURI:string){
        if(xml){
            let tempDoc=new DOMParser().parseFromString(xml)
            super(tempDoc.documentElement)
            this.doc=tempDoc
            this.rootElement=new NodeJsElement(tempDoc.documentElement)
        } else if(name) {
            let xmlStr:string
            if(namespacesURI){
                xmlStr="<"+name+" xmlns='"+namespacesURI+"' />"
            } else {
                xmlStr="<"+name+" />"
            }
            let tempDoc=new DOMParser().parseFromString(xmlStr)
            super(tempDoc.documentElement)
            this.doc=tempDoc
            this.rootElement=new NodeJsElement(tempDoc.documentElement)
        }
    }
    hasErrorTag(): boolean {
       let errorTag:Element
       if (this.doc.getElementsByTagNameNS(NS_STREAM, "error").length>0) {
           errorTag = this.doc.getElementsByTagNameNS(NS_STREAM, "error").item(0);
       } else {
           let errors = this.doc.getElementsByTagName("error");
           for (let i=0; i<errors.length; i++)
               if (errors.item(i).namespaceURI == NS_STREAM ||
                   errors.item(i).getAttribute('xmlns') == NS_STREAM) {
                   errorTag = errors.item(i);
                   break;
               }
       }
       return errorTag !=null
    }
    createElement(elementName: string): IElement {
        let tempElement=this.doc.createElement(elementName)
        return new NodeJsElement(tempElement)
    }
    createElementNS(namespaceURI: string, elementName: string): IElement {

        if(namespaceURI){
           let tempElement=this.doc.createElementNS(namespaceURI,elementName)
           return new NodeJsElement(tempElement)
        } else {
            return this.createElement(elementName)
        }
    }
    getRootElement(): IElement {
        return this.rootElement
    }
    clone():IXMLDocument {
       return new NodeJsXMLDocument(this.getRootElement().toXmlStr(),null,null)
    }

}